﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evpo.ContactData.ViewModel;
using Evpo.ContactData.Common;
using Evpo.ContactData.UI.GeneralClasses;
using Evpo.ContactData.CustomControls;

namespace Evpo.ContactData.UI
{
    public partial class ContactEdit : System.Web.UI.UserControl
    {
        #region Properties
        public bool IsReadOnly
        {
            get;
            set;
        }

        public IContact Contact
        {
            get;
            set;
        }

        public ContactEditViewModel Model
        {
            get;
            set;
        }

        protected int TitleID
        {
            get
            {
                return Int32.Parse(Request.Form[uiTitle.UniqueID]);
            }
        }

        public string LookupHiddenID
        {
            get;
            set;
        }
        #endregion

        #region Fields
        protected bool _isNewContact = true;
        #endregion

        #region Handlers
        
        protected void Page_Init(object sender, EventArgs e)
        {

            Model = new ContactEditViewModel(
                new ModelFactory(),
                (IConnection)Session[SessionStateKeys.Connection]);

            string id = Request.Params[FormParams.ID];

            Contact = Model.CreateNewContact();
            if (!String.IsNullOrEmpty(id))
            {
                _isNewContact = false;
                Contact.ContactID = Int32.Parse(id);
            }

            if (!IsPostBack)
            {
                UpdateTitleDrowDown(Model.AllTitles(), false);
                
                if (!_isNewContact)
                    Contact = Model.LoadContact(Int32.Parse(id));

            }

            uiMaritalStatus.DataSource = Model.GetMaritalStatuses();
            uiMembershipType.DataSource = Model.GetMembershipTypes();
            uiMailFormat.DataSource = Model.GetMailFormats();
            uiHomeTown.DataSource = Model.GetHomeTowns();
            PopulateContactInterests();
        }

        private void PopulateContactInterests()
        {
            uiContactInterests.Entries =
                (from item in Model.GetContactInterests()
                 select new MultiselectLookupViewEntry()
                 {
                     Value = Convert.ToString(item.ID),
                     Text = item.Name
                 }).ToList();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.DataBind();
                SetContactInterestsOfContact();
            }
        }

        protected void uiSubmit_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            Contact.TitleID = TitleID;
            Contact.FirstName = uiFirstName.Text;
            Contact.LastName = uiLastName.Text;
            Contact.IsMale = Boolean.Parse(uiSex.SelectedValue);
            Contact.Email = uiEmail.Text;
            Contact.HomePhone = uiHomePhone.Text;
            Contact.MobilePhone = uiMobilePhone.Text;
            Contact.BusinessPhone = uiBusinessPhone.Text;
            Contact.IsDeceased = uiIsDeceased.Checked;
            Contact.DateOfBirth = uiDateOfBirth.Date;
            Contact.MaritalStatus = int.Parse(uiMaritalStatus.SelectedValue);
            Contact.HomeTown = int.Parse(uiHomeTown.SelectedValue);
            Contact.MembershipType = int.Parse(uiMembershipType.SelectedValue);
            Contact.MailFormat = int.Parse(uiMailFormat.SelectedValue);
            Contact.PrimaryMailRecipient = uiPrimaryMailRecipient.Checked;

            Model.SaveContact(Contact, _isNewContact);
            Model.SaveContactInterestOfContact(Contact.ContactID, uiContactInterests.SelectedEntries);
            
            Response.Redirect(UrlHelper.ContactUrl(Contact.ContactID, Request.Url).ToString());
        }

        protected void uiNameUniqueValidation_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            var validator = (CustomValidator)sender;
            e.IsValid = false;

            if (!Model.ContactExists(
                _isNewContact, Contact.ContactID, TitleID, uiFirstName.Text, uiLastName.Text, uiDateOfBirth.Date.Value))
            {
                e.IsValid = true;
            }
        }

        #endregion Handlers

        #region Methods

        private void SetContactInterestsOfContact()
        {
            uiContactInterests.SelectedEntries =
                (from item in Model.LoadContactInterestsOfContact(Contact.ContactID)
                 select item.ID).ToList();
        }


        public void UpdateEditableLookups()
        {
            UpdateDropDown(uiHomeTown, Model.GetHomeTowns().ToList());
            PopulateContactInterests();
            UpdateTitleDrowDown(Model.AllTitles(), true);
        }

        private void UpdateTitleDrowDown(List<IDictionaryItem> items, bool saveSelected)
        {
            int selected = -1;
            if (saveSelected && !int.TryParse(uiTitle.SelectedValue, out selected))
            {
                saveSelected = false;
            }

            uiTitle.Items.Clear();

            uiTitle.Items.Add(
                new ListItem("Select title...", "not selected"));
            uiTitle.Items.AddRange(
                (from li in Model.AllTitles()
                 select new ListItem(li.Name, li.ID.ToString())).ToArray());

            if (saveSelected && 
                (from item in items
                 where item.ID == selected
                 select item).Any())
            {
                uiTitle.SelectedValue = Convert.ToString(selected);
            }

        }

        private void UpdateDropDown(SimpleDictionary dropDown, List<IDictionaryItem> items)
        {
            int selected = int.Parse(dropDown.SelectedValue);
            dropDown.DataSource = items;
            dropDown.DataBind();

            if ((from item in items
                 where item.ID == selected
                 select item).Any())
            {
                dropDown.SelectedValue = Convert.ToString(selected);
            }
        }
        #endregion Methods

        #region Classes
        private class FormParams
        {
            internal static string ID = "ID";
        }
        #endregion

        
    }

}